package com.sservice.web.controller.pc;

import com.sservice.banfu.e.SalePerson;
import com.sservice.banfu.mapper.SalePersonMapper;
import com.sservice.banfu.service.SalePersonService1;
import com.sservice.banfu.vo.SalePersonVo;
import com.sservice.base.StringUtils;
import com.sservice.base.entity.dto.BaseResult;
import com.sservice.base.entity.dto.ListResult;
import com.sservice.base.entity.dto.Pagination;
import com.sservice.common.Code;
import com.sservice.common.Constants;
import com.sservice.commonBusiness.e.Category;
import com.sservice.commonBusiness.e.DataR;
import com.sservice.commonBusiness.service.CategoryService;
import com.sservice.commonBusiness.type1.Category_TYPE;
import com.sservice.commonBusiness.vo.CategoryVo;
import com.sservice.model.entity.SalePersonAccount;
import com.sservice.model.entity.UserWx;
import com.sservice.model.vo.UserWxVo;
import com.sservice.service.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class SalePersonPcController {
    @Autowired
    ISaleLevelService iSaleLevelService;
    @Autowired
    CategoryService categoryService;
    //
    @Autowired
    ICommissionService iCommissionService; //佣金功能
    @Autowired
    IUserWxService iUserWxService;
    @Autowired
    Redis redis;
    @Autowired
    IUserWxService userWxService;
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private ISalePersonService depService;
    @Autowired
    private SalePersonMapper salePersonMapper;
    @Autowired
    private SalePersonService1 salePersonService1;
    @Autowired
    private ISalePersonAccountService spaService;

    /**
     * 创建
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public BaseResult<UserWx> get(UserWx arg) {
        UserWx service_res = userWxService.selectByPrimaryKey(arg.getId());
        return new BaseResult(true, service_res);
    }

    /**
     * 佣金记录
     *
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/history/commission", method = RequestMethod.GET)
    public ListResult commission(CategoryVo arg) {
        return iCommissionService.userCommissionApply(arg);
    }

    /**
     * 佣金
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commission", method = RequestMethod.GET)
    public BaseResult myCommission(String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        salep = userWxService.selectByPrimaryKey(salep.getId());//
        Map map = new HashMap();
        map.put("now", salep.getPointsNow());
        map.put("history", salep.getPoints());
        BaseResult listResult = new BaseResult(true, map);
        return listResult;
    }

    /**
     * 提现申请
     *
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/commission/withdraw", method = RequestMethod.GET)
    public BaseResult withdraw(Double cash, String type, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx sale = userWxService.getLogined(skey);///
        sale = userWxService.selectByPrimaryKey(sale.getId());
        if (BigDecimal.valueOf(cash).compareTo((sale.getPointsNow())) == 1) {
            return new BaseResult(false, "可提现金额不足，无法完成提现", 403);
        }
        sale.setPointsNow((sale.getPointsNow()).subtract(BigDecimal.valueOf(cash)));
        userWxService.updateByPrimaryKeySelective(sale);
        redis.setObj(skey, sale);//同步
        Category category = new Category();
        category.setpId(sale.getId().toString());//申请用户
        category.setType1(Category_TYPE.TYPE_COMMISSION_WITHDRAW.getValue());//佣金提现申请
        category.setStatus(1);//提现申请
        category.setTotal(BigDecimal.valueOf(cash));
        category.setRemark(String.valueOf(System.currentTimeMillis()));//当前毫秒哦
        BaseResult listResult = new BaseResult(true, categoryService.insertSelective(category));
        return listResult;
    }

    @ResponseBody
    @RequestMapping(value = "/queryWithDr", method = RequestMethod.GET)
    public BaseResult<UserWxVo> queryWithDr(DataR arg) {
        List<UserWxVo> service_res = iUserWxService.queryWithDr(arg);
        ListResult res = new ListResult(true, service_res);
        return res;
    }

    @RequestMapping("detail/{id}")
    @ResponseBody
    public BaseResult detail(UserWx salePerson) {

        return get(salePerson);
    }

    /**
     * 竞拍团队成员删除
     * type1
     *
     * @param salePerson
     * @return
     */
    @RequestMapping("delete/{id}")
    @ResponseBody
    public BaseResult del(SalePerson salePerson, HttpSession session) {
        SalePerson sp = salePersonMapper.selectByPrimaryKey(salePerson.getId());
        Integer t = new Integer(4);
        if (t.equals(sp.getType1())) { //  竞拍团队成员
            salePersonMapper.deleteByIds(String.valueOf(sp.getId()));
            return new BaseResult(true, "", 200);
        } else {
            return new BaseResult(false, "非法操作", 403);
        }
    }

    @ResponseBody
    @RequestMapping(value = "/logout", method = RequestMethod.GET)
    public BaseResult<Object> logout(SalePerson arg, HttpSession session) {
        BaseResult<Object> res;
        session.setAttribute("current", null);
        res = new BaseResult(true, "success");
        return res;
    }

    /**
     * 修改头像
     *
     * @param arg
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update-thumb", method = RequestMethod.POST)
    public BaseResult<Integer> updateThumb(SalePerson arg, HttpSession session) {
        SalePerson sale = (SalePerson) session.getAttribute(Constants.CURRENT_SP);
        BaseResult<Integer> res;
        if (sale != null) {
            arg.setId(sale.getId());
            int service_res = depService.updateByPrimaryKeySelective(arg);
            res = new BaseResult(true, service_res);
            sale.setAvatar(arg.getAvatar());
            session.setAttribute(Constants.CURRENT_SP, sale);
        } else {
            res = new BaseResult(false, "请登录!", 401);
        }
        return res;
    }

    /***
     * 修改数据
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public BaseResult update(UserWx arg, String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        BaseResult<Integer> res;
        if (salep != null) {
            int service_res = userWxService.updateByPrimaryKeySelective(arg);
            res = new BaseResult(true, service_res);
            UserWx sp = userWxService.selectByPrimaryKey(arg.getId());
            redis.setObj(skey, sp);
        } else {
            res = new BaseResult(false, "请登录!", 401);
        }
        return res;
    }

    /**
     * 验证手机号
     * arg.phone 手机号
     * arg.code 验证码
     *
     * @param arg
     * @param request
     * @param skey
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/verify-phone", method = RequestMethod.POST)
    public BaseResult verifyPhone(UserWxVo arg, HttpServletRequest request, String skey) {

        if (arg.getId() == null || arg.getPhone() == null || arg.getCode() == null || skey == null) {
            return new BaseResult(false, "参数不完整", Code.INCOMPLETE_PARAMETERS);//
        }
        String str = redis.get(arg.getPhone());

        if (str == null || !str.equals(arg.getCode())) { //
            return new BaseResult(false, "验证码无效", Code.INVALID_CODE);//
        }

        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) {
            return new BaseResult(false, "未登录 ", Code.NOT_LOGIN);
        }

        UserWx userWx = new UserWx();
        userWx.setPhone(arg.getPhone());
        userWx.setId(arg.getId());
        userWxService.updateByPrimaryKeySelective(userWx);
        UserWx sp = userWxService.selectByPrimaryKey(arg.getId());
        redis.setObj(skey, sp);
        return new BaseResult(true, sp);
    }


    /**
     * @param skey
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/getInfo", method = RequestMethod.GET)
    public BaseResult update(String skey) {
        if (StringUtils.isBlank(skey)) {
            return new ListResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx salep = userWxService.getLogined(skey);
        if (salep == null) { //
            return new ListResult(false, "未登录 ", 401);
        }
        BaseResult<Integer> res;
        UserWx sp = userWxService.selectByPrimaryKey(salep.getId());
        Map map = new HashMap();
        //map.put("level", iSaleLevelService.getLevel(Math.max(sp.getSalesCount(), sp.getCustomerCount()) + ""));// 上季度和本季度取最大值
        map.put("user", sp);
        return new BaseResult(true, map);
    }


    @ResponseBody
    @RequestMapping(value = "/current", method = RequestMethod.GET)
    public BaseResult<UserWx> current(String skey) {
        if (StringUtils.isBlank(skey)) {
            return new BaseResult(false, "参数不合法，未携带skey参数", 403);
        }
        UserWx sale = userWxService.getLogined(skey);
        if (sale == null) {
            return new BaseResult(false, "未登录 ", 401);
        }
        BaseResult<UserWx> res;
        if (sale != null) {
            res = new BaseResult(true, sale);
        } else {
            res = new BaseResult(false, "请登录!", 401);

        }
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/currentCashAccount", method = RequestMethod.GET)
    public BaseResult<Object> currentCashAccount(SalePerson arg, HttpSession session) {
        SalePerson sale = (SalePerson) session.getAttribute("current");
        BaseResult<Object> res;
        if (sale != null) {
            SalePersonAccount spa = spaService.selectBySaleId(String.valueOf(sale.getId()));
            Map map = new HashMap();
            map.put("account", spa);
            map.put("person", sale);
            res = new BaseResult(true, map);
        } else {
            res = new BaseResult(false, "请登录!", 401);
        }
        return res;
    }

    /***
     * 分页查询
     * @param arg
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/query", method = RequestMethod.GET)
    public ListResult<SalePerson> query(SalePersonVo arg) {
        List<SalePersonVo> list = salePersonService1.page(arg);
        int total = salePersonService1.count(arg);
        Pagination page = new Pagination(arg.getPage(), total, arg.getSize());
        ListResult<SalePerson> res = new ListResult(true, list);
        res.setPage(page);
        return res;
    }

    @ResponseBody
    @RequestMapping(value = "/mySales", method = RequestMethod.GET)
    public ListResult<SalePerson> queryMySales(SalePerson arg, HttpSession session) {
        SalePerson sp = (SalePerson) session.getAttribute(Constants.CURRENT_SP);
        if (sp == null) {
            return new ListResult(false, "未登录", 401);
        }
        List<SalePerson> list = depService.queryByUserIdAndPage(arg);
        depService.queryCount(null);
        ListResult<SalePerson> res = new ListResult(true, list);
        return res;
    }


}
